package com.zkingsoft.actions.admin;

import com.zkingsoft.services.CourseService;
import com.zkingsoft.services.DataDictionaryService;
import com.zkingsoft.services.StudentinfoService;
import com.zkingsoft.services.TabClassService;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zkingsoft.actions.common.BaseController;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.serviceUtil.ServiceUtil;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ExcelImport;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.plugin.util.FileDownload;
import com.zkingsoft.plugin.util.FileUtils;
import com.zkingsoft.plugin.util.WebUtil;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.model.Course;
import com.zkingsoft.model.DataDictionary;
import com.zkingsoft.model.Studentinfo;
import com.zkingsoft.model.TabClass;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.BusinessConstance;
import com.zkingsoft.exception.GlobleException;

/**
 * 学生管理
 * @date 2017-06-08 17:19
 * @author xiefeng
 */
@Controller
@RequestMapping(value = "admin/studentinfo")
public class StudentinfoController extends BaseController{

	@Resource
	private StudentinfoService currentService;
	@Resource
	private DataDictionaryService dataDictionaryService;
	@Resource
	private TabClassService tabClassService;
	@Resource
	private CourseService courseService;
	@Resource
	private ServiceUtil serviceUtil;
	
	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Studentinfo studentinfo, PaginationVO pageVo) {
		pageVo.setSort("stu_date");
		pageVo.setOrder("desc");
		return showList(currentService, studentinfo, pageVo);
	}
   	
	/**
	 * 新增或者修改页面
	 */   
	@RemoveRequestToken	
   	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(Studentinfo studentinfo) {
		if(studentinfo.getStuPmoney()>studentinfo.getStuTuition()){
			 throw new GlobleException("优惠金额不能大于学费标准");
		}
		if (studentinfo.getStuId() != null) {
			return modify(currentService, studentinfo, "学生");
		} else {
			//判断学生姓名是否存在，如果存在相同的给出提示。
			if(serviceUtil.addCheckRepeat("studentinfo", "stu_name", studentinfo.getStuName())){
				throw new GlobleException("有相同学生姓名存在，请在姓名后面加上区分学生的备注！");
			}
			return add(currentService, studentinfo, "学生");
		}
	}
	
   	/**
	 * 进入修改界面
	 */   
	@SaveRequestToken
   	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		Studentinfo studentinfo;
		if (id != null) {
			studentinfo = currentService.findById(id);
			WebUtil.getRequest().setAttribute("obj", studentinfo);
		}
		return "admin/studentinfo-form";
	}
   	
   	
   	/**
	 * 删除
	 */  
 	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(currentService, keys);
	}
  
	//查询所有的院校
 	@RequestMapping(value = "/showAllSchool")
	public @ResponseBody AjaxResult showAllSchool() {
 		DataDictionary dataDictionary = new DataDictionary();
 		dataDictionary.setType(BusinessConstance.DATA_TYPE_SCHOOL);
 		List<DataDictionary> schoolList = dataDictionaryService.findByModel(dataDictionary);
 		if(schoolList!=null && schoolList.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"成功",schoolList,schoolList.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR,null,"失败");
	}
 	
 	//查询所有的缴费方式
 	@RequestMapping(value = "/showAllPay")
	public @ResponseBody AjaxResult showAllPay() {
 		DataDictionary dataDictionary = new DataDictionary();
 		dataDictionary.setType(BusinessConstance.DATA_TYPE_PAY_TYPE);
 		List<DataDictionary> payList = dataDictionaryService.findByModel(dataDictionary);
 		if(payList!=null && payList.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"成功",payList,payList.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR,null,"失败");
	}
 	
 	//查询所有的学生状态
 	@RequestMapping(value = "/showStuStatus")
	public @ResponseBody AjaxResult showStuStatus() {
 		DataDictionary dataDictionary = new DataDictionary();
 		dataDictionary.setType(BusinessConstance.DATA_TYPE_STUD_STATUS);
 		List<DataDictionary> stuStatusList = dataDictionaryService.findByModel(dataDictionary);
 		if(stuStatusList!=null && stuStatusList.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"成功",stuStatusList,stuStatusList.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR,null,"失败");
	}
 	
 	/**
	 * @Description:查询所有的学生姓名
	 * @author:
	 * @return
	 * 返回类型 AjaxResult
	 * @date 2017年5月5日
	 */
	@RequestMapping(value = "/showAllStudent")
	public @ResponseBody AjaxResult showAllStudent() {
 		List<Studentinfo> stuList = currentService.findByModel(null);
 		if(stuList!=null && stuList.size()>0){
 			return new AjaxResult(AjaxResult.STATUS_OK,null,"成功",stuList,stuList.size());
 		}
 		return new AjaxResult(AjaxResult.STATUS_ERR,null,"失败");
	}
	
	
	/**
 	 * 
 	 * @Description:导出excel
 	 * @author:dingchuan
 	 * @return
 	 * 返回类型 ModelAndView
 	 * @date 2017年2月13日
 	 */
 	@RequestMapping(value = "/exportExcel")
 	public @ResponseBody ModelAndView report(ModelMap model, HttpServletRequest request, HttpServletResponse response,
 			Studentinfo studentInfo) {
 	    try {
 	        if (studentInfo.getStuName() != null && !(studentInfo.getStuName().equals(""))) {
 	        	studentInfo.setStuName(java.net.URLDecoder.decode(studentInfo.getStuName(), "UTF-8"));
 	        }
 	    } catch (UnsupportedEncodingException e1) {
 	        e1.printStackTrace();
 	    }
 	  /*  // 查询符合条件的数据
 	    String tClass = studentInfo.gettClass();
		if(tClass!=null && !"".equals(tClass)){
			TabClass tabClass = tabClassService.findById(Long.parseLong(tClass));
			if(tabClass!=null){
				studentInfo.settClass(tabClass.getClaName());
			}
		}*/	    
 	    List<Studentinfo> dataList = currentService.findByModel(studentInfo);
 	    //把数据组装成我们要的数据，外面的list表示一行数据，也就是一个对象的信息，对应到excel的一行数据。里面的list表示对象的一个属性，对应excel的单元格
 	    SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
 	    List<List< Object>> list = new ArrayList<>();
 	        for (Studentinfo obj : dataList) {
 	            List<Object> temp = new ArrayList<>();
 	            temp.add(obj.getStuNo());
 	            temp.add(obj.getStuName());
 	            temp.add(obj.getStuSchool());
 	            temp.add(obj.getStuIfschool());
 	            temp.add(obj.getClaName());
 	            temp.add(obj.getCouName());
 	            temp.add(obj.getStuTuition());
 	            temp.add(obj.getStuMode());
 	            temp.add(obj.getStuPmoney());
 	            temp.add(obj.getStuCause());
 	            temp.add(obj.getPayable());
 	            String dateStr = sdf.format(obj.getStuDate());
	            temp.add(dateStr);
	            temp.add(obj.getStuStatus());
	            temp.add(obj.getTcName());
 	            temp.add(obj.getStuRemark());
 	            list.add(temp);
 	        }
 	    //调用我们的excel工具类，导出数据
 	    HSSFWorkbook workbook = ExcelUtil.generateExcel("学生管理大学部学生列表",
 	            new String[] { "学号","姓名","来自院校","是否院校毕业","所在班级","课程",
 	            		"学费标准","缴费方式","优惠金额","优惠原因","应交学费","入学时间","状态","班主任","备注"}, list);
 	    try {
 	        ViewExcel.buildExcel(null, workbook, request, response, "学生管理大学部学生列表.xls");
 	    } catch (Exception e) {
 	        e.printStackTrace();
 	    }
 	    return new ModelAndView(new ViewExcel(), model);
 	}
 	
 	/**
 	 * @Description:下载模板
 	 * @author:dingchuan
 	 * @param response
 	 * @throws Exception
 	 * 返回类型 void
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value="/downExcelModel")
   	public void downExcelModel(HttpServletResponse response) throws Exception{
   		String path = WebUtil.getResourceRealPath("WEB-INF/views/admin/studentinfo_import_model.xlsx");   		
   		FileDownload.fileDownload(response, path, "学生管理-大学部导入模板.xlsx");
   	}
 	
 	private static final Logger log = Logger.getLogger(StudentinfoController.class);
 	
 	
 	
 	/**
 	 * @Description:导入excel
 	 * @author:dingchuan
 	 * @param response
 	 * @param request
 	 * @param file
 	 * @return
 	 * 返回类型 AjaxResult
 	 * @date 2017年2月14日
 	 */
 	@RequestMapping(value = "/importData")
	public @ResponseBody AjaxResult importData(HttpServletResponse response, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file) {
		// 记录成功的导入多少条数据
		int count = 0;
		// 构造对象的集合
		List<Studentinfo> studentList = new ArrayList<Studentinfo>();
		response.setContentType("text/html;charset=UTF-8");
		String fileName = file.getOriginalFilename();
		String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1);
		if (!extension.equals("xls") && !extension.equals("xlsx")) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "请选择excel文件！！！");
		}
		String dirPath = request.getSession().getServletContext().getRealPath("/") + "fileupload";
		File fileDir = new File(dirPath);
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		try {
			if (!fileDir.exists()) {
				if (fileDir.mkdirs()) {
				}
			}
			File saveFile = new File(dirPath + "/" + fileName);
			file.transferTo(saveFile);
			List<List<Object>> list = ExcelImport.readExcel(saveFile, fileName, null, 14);
			// 由于读取excel的工具类会从标题行开始读取，因此，list=null或者size=1表示只有标题行说明没有数据可以导入
			if (list == null || list.size() <= 1) {
				throw new GlobleException("没有数据可导入");
			}
			for (int i = 2; i < list.size(); i++) {//表格第一行是标题，从第二行开始遍历
				Studentinfo student = new Studentinfo();//每一行
				List<Object> objList = list.get(i);
				int t = i+1;
				//student.setStuNo(currentService.createStuNo());
				if(objList.get(0)==null){
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的学号没有填写");
				}else{
					String stuNo = ((String) objList.get(0)).trim();//学号
					student.setStuNo(stuNo);
				}
				
				if(objList.get(1)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的学生姓名没有填写");
   	   			}else{
   	   				String stuName = ((String)objList.get(1)).trim();//学生姓名
   	   				student.setStuName(stuName);
   	   			}
				
				if(objList.get(2)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的来自院校没有填写");
   	   			}else{
   	   				String sSchool = ((String)objList.get(2)).trim();//来自院校
   	   				student.setStuSchool(sSchool);
   	   			}
				
				if(objList.get(3)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的是否院校毕业没有填写");
   	   			}else{
   	   				String sSchool = ((String)objList.get(3)).trim();//是否校院毕业
   	   				student.setStuIfschool(sSchool);
   	   			}
				
				if(objList.get(4)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班级id没有填写");
   	   			}else{
   	   				String classId = ((String)objList.get(4)).trim();//班级id
	   	   			String str1;
		   				if(classId.contains(".")){
	   					str1 = classId.substring(0, classId.length()-3);
	   				}else{
	   					str1 = classId;
	   				}
	   	   			try {
	   	   				Long id = tabClassService.findByName(str1);//根据名称查找出id，(把表格中的String类型转成数字存入Id)
	   	   				//Long sClass = Long.valueOf(id);			//得到班级id
	   	   				TabClass tabClass = tabClassService.findById(id);
	   	   				if(tabClass==null){
	   	   					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班级不存在");
	   	   				}else{
	   	   					student.setStuClass(id);
	   	   				}
		   			} catch (Exception e) {
		   				log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班级不存在");
					}
   	   			}
				
				if(objList.get(5)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的课程没有填写");
   	   			}else{
   	   				String sNumber1 = ((String)objList.get(5)).trim();//课程mingceng
	   	   			String str1;
	   				if(sNumber1.contains(".")){
						str1 = sNumber1.substring(0, sNumber1.length()-3);
					}else{
						str1 = sNumber1;
					}
	   	   			try {
	   	   				//根据课程名称来找课程id
	   	   				long id=courseService.findByName(str1);
	   	   				
	   	   				Long courseId = Long.valueOf(id);
	   	   				
	   	   				Course course = courseService.findById(courseId); 
	   	   				
	   	   				if(course==null){
	   	   					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的课程不存在");
	   	   				}else{
	   	   					student.setStuCourse(courseId);
	   	   				}
		   			} catch (Exception e) {
		   				log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的课程不存在");
					}
   	   			}
				
				if(objList.get(6)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的学费标准没有填写");
   	   			}else{
   	   				String couCostStr = ((String)objList.get(6)).trim();//学费标准
   	   				String str1;
   	   				if(couCostStr.contains(".")){
   	   					str1 = couCostStr.substring(0, couCostStr.length()-3);
   	   				}else{
   	   					str1 = couCostStr;
   	   				}
	   	   			try {
	   	   				Double tStandard = Double.valueOf(str1);
	   	   				student.setStuTuition(tStandard);
		   			} catch (Exception e) {
		   				log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的学费标准填写的不是数字");
					}
   	   			}
				
				if(objList.get(7)==null){
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的缴费方式没有填写");
				}else{
					String tPaying = ((String)objList.get(7)).trim();//缴费方式
					student.setStuMode(tPaying);
				}
				
				if(objList.get(8)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的优惠金额没有填写");
   	   			}else{
   	   				String couCostStr = ((String)objList.get(8)).trim();//优惠金额
   	   				String str1;
   	   				if(couCostStr.contains(".")){
   	   					str1 = couCostStr.substring(0, couCostStr.length()-3);
   	   				}else{
   	   					str1 = couCostStr;
   	   				}
	   	   			try {
	   	   				Double tPrivilege = Double.valueOf(str1);
	   	   				student.setStuPmoney(tPrivilege);
		   			} catch (Exception e) {
		   				log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的优惠金额填写的不是数字");
					}
   	   			}
				
				if(objList.get(9)==null){
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的优惠原因没有填写");
				}else{
					String tCause = ((String)objList.get(9)).trim();//优惠原因
					student.setStuCause(tCause);
				}
				
				if(objList.get(10)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的应交学费没有填写");
   	   			}else{
   	   				String couCostStr = ((String)objList.get(10)).trim();//应交学费
   	   				String str1;
   	   				if(couCostStr.contains(".")){
   	   					str1 = couCostStr.substring(0, couCostStr.length()-3);
   	   				}else{
   	   					str1 = couCostStr;
   	   				}
	   	   			try {
	   	   				Double tTuition = Double.valueOf(str1);
	   	   				student.setPayable(tTuition);
		   			} catch (Exception e) {
		   				log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的应交学费填写的不是数字");
					}
   	   			}
				
				if(objList.get(11)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的入学时间没有填写");
   	   			}else{
   	   				String uJobdate = ((String)objList.get(11)).trim();//入学时间
   	   				Date date;
   	   				try {
   	   					date = sdf.parse(uJobdate);
					} catch (Exception e) {
						log.debug(e.toString());
		   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的入职时间填写格式不正确");
					}
   	   				student.setStuDate(date);
   	   			}
				
				if(objList.get(12)==null){
					return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的学生状态没有填写");
				}else{
					String sOption1 = ((String)objList.get(12)).trim();//学生状态
					student.setStuStatus(sOption1);
				}	
				
				if(objList.get(13)==null){
   	   				return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班主任没有填写");
   	   			}else{
   	   				String tTeacher = ((String)objList.get(13)).trim();//班主任
   	   				student.setTcName(tTeacher);
   	   			}
				
				if(objList.get(14)==null){
				}else{
					String sRemark = ((String)objList.get(14)).trim();//备注
					student.setStuRemark(sRemark);
				}
				//判断学生是否存在、
				if(serviceUtil.addCheckRepeat("studentinfo", "stu_name", student.getStuName())){
					  throw new GlobleException("导入失败!因为第"+t+"行的学生姓名已经存在");
				}
				//判断学号是否存在
				if(serviceUtil.addCheckRepeat("studentinfo", "stu_no", student.getStuNo())){
					  throw new GlobleException("导入失败!因为第"+t+"行的学号已经存在");
				}
				studentList.add(student);	
			}
			count =	currentService.adds(studentList);
		} catch (IOException e) {	
			log.error("导入异常");
		}finally {
			FileUtils.deleteDir(fileDir);
		}
		if (count > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "成功导入" + count + "条数据!");
		} else {
			return new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!");
		}
	}
}